package com.inforich.app.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.common.collect.Lists;
import com.inforich.app.api.service.IOpenService;
import com.inforich.app.utils.BASE64DecodedMultipartFile;
import com.inforich.common.config.InforichConfig;
import com.inforich.common.core.domain.AjaxResult;
import com.inforich.common.utils.JsonUtil;
import com.inforich.common.utils.file.FileUploadUtils;
import com.inforich.disposal.domain.DisposalLand;
import com.inforich.disposal.domain.DisposalLandTerminalVehicleApproach;
import com.inforich.disposal.service.IDisposalLandService;
import com.inforich.disposal.service.IDisposalLandTerminalVehicleApproachService;
import com.inforich.framework.config.ServerConfig;
import com.inforich.projectManage.domain.Project;
import com.inforich.projectManage.service.IProjectService;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


/**
 * @description: some desc
 * @author: HJM
 * @date: 2022/11/4
 */
@Service
public class OpenServiceImpl implements IOpenService {

  protected final Logger logger = LoggerFactory.getLogger(getClass());
  @Autowired
  private IDisposalLandTerminalVehicleApproachService approachService;
  @Autowired
  private IProjectService projectService;
  @Autowired
  private IDisposalLandService disposalLandService;
  // 通用型秘钥
  private static final String KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcA";

  private static final Map<String, Long> APP_KEY_MAP;

  static {
    APP_KEY_MAP = new HashMap<>();
    // 江苏远康
    APP_KEY_MAP.put("decd04101e0f436dbf6a588ab7b80ae3", 1L);
    // 南京龙冠
    APP_KEY_MAP.put("ffb2e36de70f48aab8e66fc57cde07ba", 2L);
    // 南京荣赋
    APP_KEY_MAP.put("e00046d2aea9402291f5e6e58edc22e4", 3L);
    // 南京宁正
    APP_KEY_MAP.put("4f5099be22fa44d5aacd3d33176892cb", 4L);
    // 南京杰通
    APP_KEY_MAP.put("6baa37aabed64adfb6d5a6333ca2fa63", 16L);
    // 南京强旺
    APP_KEY_MAP.put("84cbf0fd0a1f46c3a1368df68be427a7", 17L);
  }

  @Override
  public AjaxResult uploadVehicleApproach(JSONObject json) {
    try {
      JSONArray array = json.getJSONArray("data");
      Long disposalLandId = getDisposalLandId(json);
      if (disposalLandId == null) {
        logger.error("处置厂上传数据失败,秘钥不正确 disposalLandId: " + disposalLandId);
        return AjaxResult.error("秘钥不正确,不允许上传");
      }
      if (CollUtil.isEmpty(array)) {
        logger.error("处置厂上传数据失败,无数据");
        return AjaxResult.error("无有效数据");
      }
      if (array.size() > 500) {
        logger.error("处置厂上传数据失败,超过数量限制");
        return AjaxResult.error("数据超过限制");
      }
      Map<String, String> projectNameIdMap = getProjectNameIdMap();
      List<DisposalLandTerminalVehicleApproach> list = Lists.newArrayList();
      logger.info("开始上传处置厂称重数据 disposalLandId: " + disposalLandId + " 数据量: " + array.size());
      for (int i = 0; i < array.size(); i++) {
        JSONObject o = array.getJSONObject(i);
        list.add(createApproach(disposalLandId, o, projectNameIdMap));
      }
      approachService.saveBatch(list);
      // 更新资源化利用企业最后上传时间
      disposalLandService.update(new LambdaUpdateWrapper<DisposalLand>()
          .set(DisposalLand::getFinalDataReportTime, new Date())
          .eq(DisposalLand::getId, disposalLandId));
      return AjaxResult.success("上传成功");
    } catch (Exception e) {
      logger.error("上传处置终端车辆进场明细数据失败: ", e);
      return AjaxResult.error(e.getMessage());
    }
  }

  /**
   * 获取处置厂ID
   */
  private Long getDisposalLandId(JSONObject json) {
    String key = json.getString("key");
    Long disposalLandId;
    if (KEY.equals(key)) {
      disposalLandId = json.getLong("disposalLandId");
      if (disposalLandId != null) {
        return disposalLandId;
      }
    }
    disposalLandId = APP_KEY_MAP.get(key);
    return disposalLandId;
  }

  /**
   * 项目名称->ID
   */
  private Map<String, String> getProjectNameIdMap() {
    List<Project> projectList = projectService.listProject(new HashMap<>());
    Map<String, String> map = new HashMap<>();
    projectList.forEach(p -> map.put(p.getName(), p.getId()));
    return map;
  }

  /**
   * 数据转换
   */
  private DisposalLandTerminalVehicleApproach createApproach(Long disposalLandId, JSONObject o,
      Map<String, String> projectNameIdMap) {
    DisposalLandTerminalVehicleApproach approach = new DisposalLandTerminalVehicleApproach();
    String projectId = projectNameIdMap.get(o.getString("项目信息"));
    approach.setDisposalLandId(disposalLandId);
    approach.setProjectId(projectId);
    approach.setSerialNumber(o.getString("流水号"));
    approach.setCarNumber(o.getString("车牌号"));
    approach.setShipper(StrUtil.blankToDefault(o.getString("发货单位"), o.getString("项目信息")));
    approach.setReceivingUnit(o.getString("收货单位"));
    approach.setReceivingAddress(o.getString("收货地址"));
    approach.setGoodsName(o.getString("货名"));
    approach.setSpecification(o.getString("规格"));
    approach.setGrossWeightman(o.getString("毛重司磅员"));
    approach.setTareWeigher(o.getString("皮重司磅员"));
    approach.setGrossHeavyweight(o.getString("毛重磅号"));
    approach.setTareHeavy(o.getString("皮重磅号"));
    approach.setGrossWeightTime(o.getDate("毛重时间"));
    approach.setTareTime(o.getDate("皮重时间"));
    approach.setWeighingTime(o.getDate("一次过磅时间"));
    approach.setSecondWeighingTime(o.getDate("二次过磅时间"));
    approach.setGarbageWeight(o.getBigDecimal("垃圾重量"));
    approach.setGrossWeight(o.getBigDecimal("毛重"));
    approach.setTare(o.getBigDecimal("皮重"));
    approach.setDeduction(o.getBigDecimal("扣重"));
    approach.setNetWeight(o.getBigDecimal("净重"));
    approach.setUnitPrice(o.getBigDecimal("单价"));
    approach.setAmount(o.getBigDecimal("金额"));
    approach.setFactor(o.getBigDecimal("折方系数"));
    approach.setSquareAmount(o.getBigDecimal("方量"));
    approach.setWeighingFee(o.getBigDecimal("过磅费"));
    approach.setOneWeighing(o.getBigDecimal("一次过磅重"));
    approach.setSecondWeighing(o.getBigDecimal("二次过磅重"));
    approach.setGarbageType(o.getLong("垃圾类型"));
    approach.setWeighingType(o.getLong("过磅类型"));
    approach.setGrossImg(createGrossImg(o));
    approach.setTareImg(createTareImg(o));
    return approach;
  }

  /**
   * 生成毛重图片
   */
  private String createGrossImg(JSONObject o) {
    String GROSS_IMG1 = o.getString("GROSS_IMG1");
    if (StrUtil.isNotBlank(GROSS_IMG1)) {
      return createPic(GROSS_IMG1);
    }
    String GROSS_IMG2 = o.getString("GROSS_IMG2");
    if (StrUtil.isNotBlank(GROSS_IMG2)) {
      return createPic(GROSS_IMG2);
    }
    String GROSS_IMG3 = o.getString("GROSS_IMG3");
    if (StrUtil.isNotBlank(GROSS_IMG3)) {
      return createPic(GROSS_IMG3);
    }
    String GROSS_IMG4 = o.getString("GROSS_IMG4");
    if (StrUtil.isNotBlank(GROSS_IMG4)) {
      return createPic(GROSS_IMG4);
    }
    String GROSS_IMG5 = o.getString("GROSS_IMG5");
    if (StrUtil.isNotBlank(GROSS_IMG5)) {
      return createPic(GROSS_IMG5);
    }
    String GROSS_IMG6 = o.getString("GROSS_IMG6");
    if (StrUtil.isNotBlank(GROSS_IMG6)) {
      return createPic(GROSS_IMG6);
    }
    return "";
  }

  /**
   * 生成净重图片
   */
  private String createTareImg(JSONObject o) {
    String TARE_IMG1 = o.getString("TARE_IMG1");
    if (StrUtil.isNotBlank(TARE_IMG1)) {
      return createPic(TARE_IMG1);
    }
    String TARE_IMG2 = o.getString("TARE_IMG2");
    if (StrUtil.isNotBlank(TARE_IMG2)) {
      return createPic(TARE_IMG2);
    }
    String TARE_IMG3 = o.getString("TARE_IMG3");
    if (StrUtil.isNotBlank(TARE_IMG3)) {
      return createPic(TARE_IMG3);
    }
    String TARE_IMG4 = o.getString("TARE_IMG4");
    if (StrUtil.isNotBlank(TARE_IMG4)) {
      return createPic(TARE_IMG4);
    }
    String TARE_IMG5 = o.getString("TARE_IMG5");
    if (StrUtil.isNotBlank(TARE_IMG5)) {
      return createPic(TARE_IMG5);
    }
    String TARE_IMG6 = o.getString("TARE_IMG6");
    if (StrUtil.isNotBlank(TARE_IMG6)) {
      return createPic(TARE_IMG6);
    }
    return "";
  }

  /**
   * 保存BASE64->图片
   */
  private String createPic(String base64) {
    if (StrUtil.isBlank(base64)) {
      return "";
    }
    MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(
        "data:image/jpg;base64," + base64);
    try {
      // 上传文件路径
      String filePath = InforichConfig.getUploadPath();
      // 上传并返回新文件名称
      return FileUploadUtils.upload(filePath, file);
    } catch (Exception e) {
      return "";
    }
  }

  public static void main(String[] args) {
    OpenServiceImpl open = new OpenServiceImpl();
    System.out.println(
        open.getDisposalLandId(JsonUtil.of("key", "84cbf0fd0a1f46c3a1368df68be427a7")));
  }

}
